package com.ycz.sportplay.controller;

import com.alibaba.fastjson.JSON;
import com.ycz.sportplay.bean.QueryInfo;
import com.ycz.sportplay.bean.User;
import com.ycz.sportplay.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description
 * @ClassName UserController
 * @Author yanchengzhi
 * @date 2022.06.17 19:50
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/getList")
    public String getUserList(@RequestBody QueryInfo queryInfo) {
        int total = userService.getUserCounts(queryInfo.getQuery());
        int pageStart = (queryInfo.getPageNo() - 1) * queryInfo.getPageSize();
        List<User> users = userService.getUserList(queryInfo.getQuery(), pageStart, queryInfo.getPageSize());
        Map<String, Object> map = new HashMap<>();
        map.put("total", total);
        map.put("users", users);
        String res = JSON.toJSONString(map);
        return res;
    }

    @PutMapping("/updateState")
    public String updateState(@RequestParam("id") Integer id,@RequestParam("state") Boolean state) {
        int res = userService.updateState(id,state);
        return res > 0  ? "success" : "error";
    }

    @PostMapping("/addUser")
    public String addUser(@RequestBody User user) {
        user.setRole("普通用户");
        user.setState(false);
        int res = userService.addUser(user);
        return res > 0 ? "success" : "error";
    }

    @DeleteMapping("/deleteUser")
    public String deleteUser(@RequestParam("id") Integer id) {
        int res = userService.deleteUser(id);
        return res > 0 ? "success" : "error";
    }

    @GetMapping("/getUser")
    public String getUser(@RequestParam("id") Integer id) {
        User user = userService.getUserById(id);
        String res = JSON.toJSONString(user);
        return res;
    }

    @PutMapping("/editUser")
    public String updateUser(@RequestBody User user) {
        int res = userService.editUser(user);
        return res > 0 ? "success" : "error";
    }

}
